const { MailParser } = require('mailparser');
const notifier = require('node-notifier');
const path = require('path');
const Imap = require('imap');
const userConfig = require('./config.js')
// 接收邮件服务器： imap.qq.com，使用SSL，端口号993
const imap = new Imap({
    user: userConfig.user,
    password: userConfig.password,
    host: 'imap.qq.com',
    port: 993,
    tls: true
});


// 连接到IMAP服务器
imap.connect();

// 当连接成功时
imap.once('ready', () => {
    // 打开收件箱
    imap.openBox('INBOX', true, (err, box) => {
        if (err) throw err;
        console.log('Connected to INBOX');

        // 获取今天启动时间
        const today = new Date();
        today.setHours(0, 0, 0, 0);
        const startDate = today.toISOString();

        // 构建搜索条件，搜索从今天启动时间之后的新邮件
        const searchCriteria = ['UNSEEN', ['SINCE', startDate]];

        // 监听新邮件事件
        imap.on('mail', () => {
            console.log('Received new message(s)');

            // 搜索未读邮件 添加搜索条件
            imap.search(searchCriteria, (err, results) => {
                if (err) throw err;

                // 获取最新的邮件
                const f = imap.fetch(results, { bodies: '' });
                f.on('message', (msg, seqno) => {
                    const mailparser = new MailParser();
                    msg.on('body', (stream) => {
                        const info = {};
                        stream.pipe(mailparser);
                        mailparser.on("headers", (headers) => {
                            info.theme = headers.get('subject');
                            info.form = headers.get('from').value[0].address;
                            info.mailName = headers.get('from').value[0].name;
                            info.to = headers.get('to').value[0].address;
                            info.datatime = headers.get('date').toLocaleString();
                        });

                        mailparser.on("data", (data) => {
                            // 添加判断逻辑
                            if (info.form.toString().includes('biya')) {
                                let text = data.text
                                let regex;
                                const regexCn = /验证码是\n+\s*\n+(\d+)\n+/;
                                const regexEn = /code is\n+\s*\n+(\d+)\n+/;
                                regex = text.includes('验证码') ? regexCn : regexEn;
                                const match = text.match(regex);
                                const verificationCode = match ? match[1] : '';

                                notifier.notify({
                                    title: info.form,
                                    message: verificationCode,
                                    icon: path.join(__dirname, 'mail.png')
                                });
                                console.warn(verificationCode); // 输出验证码
                            }

                            // 文件类型判断自动下载到指定文件夹
                            // if (data.type === 'text') {
                            //     info.html = data.html;
                            //     info.text = data.text;

                            //     const filePath = path.join(__dirname, 'mails', info.theme + '.html');
                            //     fs.writeFileSync(filePath, info.html || info.text)

                            //     console.log(info);
                            // }
                            // if (data.type === 'attachment') {
                            //     const filePath = path.join(__dirname, 'files', data.filename);
                            //     const ws = fs.createWriteStream(filePath);
                            //     data.content.pipe(ws);
                            // }

                        })
                    });
                });

                // 标记邮件为已读
                f.on('end', () => {
                    imap.addFlags(results, 'Seen', (err) => {
                        if (err) console.error(err);
                    });
                });
            });
        });
    });
});

// 连接错误处理
imap.once('error', (err) => {
    console.error(err);
});

// 连接断开处理
imap.once('end', () => {
    console.log('Connection ended');
});
